package com.pentajock.docdb.gui;

import com.pentajock.docdb.types.Document;
import javax.swing.*;
import java.util.List;
import java.io.File;
import java.util.Arrays;

public class DocumentResultListModel extends DefaultListModel {
	/* 
	 * For last-minute filtering 
	 */
	public static enum Filter {
		APPROVED;
	}
	
	private boolean listenersEnabled;

	public DocumentResultListModel() {
		super();
		listenersEnabled = true;
	}
	
	public void addAll(List all) {
		if (all == null) return;
		setListenersEnabled(false);
		for (Object o : all) addElement(o);
		setListenersEnabled(true);
		fireContentsChanged(this, 0, getSize());
		fireIntervalAdded(this, 0, getSize());
	}
	
	public void addAll(Object[] all) {
		addAll(Arrays.asList(all));
	}
	
	public void addAll(List all, String filter) {
		setListenersEnabled(false);
		for(Object o : all)
			if(o != null && (filter == null || o.toString().toLowerCase().startsWith(filter.toLowerCase())))
				addElement(o);
		setListenersEnabled(true);
		fireContentsChanged(this, 0, getSize());
		fireIntervalAdded(this, 0, getSize());
	}
	
	public void addAll(List all, Filter filter) {
		setListenersEnabled(false);
		for(Object o : all) {
			switch (filter) {
				case APPROVED:
					if (o instanceof Document && ((Document)o).isApproved())
						addElement(o);
					break;
				default: addElement(o);
			}
		}
		setListenersEnabled(true);
		fireContentsChanged(this, 0, getSize());
		fireIntervalAdded(this, 0, getSize());
	}
	
	public void addElement(Object o, Filter filter) {
		setListenersEnabled(false);
		switch (filter) {
		case APPROVED:
			if (o instanceof Document && ((Document)o).isApproved())
				super.addElement(o);
			break;
		default: 
			super.addElement(o);
		}
		setListenersEnabled(true);
		fireContentsChanged(this, 0, getSize());
		fireIntervalAdded(this, 0, getSize());
	}
	
	public int getRelevantSize() {
		int size = super.getSize();
		for (int i = 0; i < super.getSize(); i++)
			if (super.getElementAt(i).toString().startsWith("~"))
				size--;
		return size;
	}
	
	protected boolean getListenersEnabled() {
		return listenersEnabled;
	}
	
	protected void setListenersEnabled(boolean enabled) {
		listenersEnabled = enabled;
	}
	
	protected void fireContentsChanged(Object source, int index0, int index1) {
		if(getListenersEnabled())
			super.fireContentsChanged(source, index0, index1);
	}
	
	protected void fireIntervalAdded(Object source, int index0, int index1) {
		if(getListenersEnabled())
			super.fireIntervalAdded(source, index0, index1);
	}
	
	protected void fireIntervalRemoved(Object source, int index0, int index1) {
		if(getListenersEnabled())
			super.fireIntervalAdded(source, index0, index1);
	}
}
